<?php

/**
 * @author Murat Cem YALIN <muratcem@gmail.com>
 * @copyright 2014 muratcem.com - walkerPHP.com
 * @license http://opensource.org/licenses/GPL-3.0 GNU General Public License, version 3
 * @version 1.0.1
 */

namespace core\Session;

use \core\Config\Config;

class Session implements ISession, IOnline{
    private static $instance;
    private $vars;

    public function __construct()
    {
        static::$instance = $this;

        if (!session_id()){
            session_start();
        }

	    $this->vars =& $_SESSION[Config::get('siteSettings.sessionName')];
    }

    public static function start()
    {
        return new static();
    }

    public static function getCurrent()
    {
        return static::$instance ? static::$instance : static::start();
    }

    public static function logout()
    {
        $session = static::getCurrent();

        foreach(array_keys($session->vars) as $key){
            unset($session->vars[$key]);
        }

        if (session_id()){
            session_destroy();
            session_regenerate_id(TRUE);
        }

    }

    public function get($key = '', $default = NULL)
    {
        return array_get($this->vars, $key, $default);
    }

    public function set($key = '', $value = '')
    {
        array_set($this->vars, $key, $value);
    }

    public function delete($key = '')
    {
        array_forget($this->vars, $key);
    }

    public function __get($key)
    {
        return $this->get($key);
    }

    public function __isset($key){
        return (array_get($this->vars, $key) !== NULL);
    }

    public function __unset($key){
        array_forget($this->vars, $key);
    }

    public function writeAccess()
    {
        // TODO: session açılma bilgisi db deki sys_session tablosuna kaydedilecek
    }

    public function online()
    {
        // TODO: user auth olmuş ise sys_online tablosuna girilecek
    }

    public function ip_address()
    {
        $ipAddress = null;
        if (array_get($_SERVER, 'HTTP_CLIENT_IP')){
            $ipAddress = array_get($_SERVER, 'HTTP_CLIENT_IP');
        } elseif (array_get($_SERVER, 'HTTP_X_FORWARDED_FOR')){
            $ipAddress = array_get($_SERVER, 'HTTP_X_FORWARDED_FOR');
        } elseif (array_get($_SERVER, 'HTTP_X_FORWARDED')){
            $ipAddress = array_get($_SERVER, 'HTTP_X_FORWARDED');
        } elseif (array_get($_SERVER, 'HTTP_FORWARDED_FOR')){
            $ipAddress = array_get($_SERVER, 'HTTP_FORWARDED_FOR');
        } elseif (array_get($_SERVER, 'HTTP_FORWARDED')){
            $ipAddress = array_get($_SERVER, 'HTTP_FORWARDED');
        } else {
            $ipAddress = array_get($_SERVER, 'REMOTE_ADDR');
        }
        return $ipAddress;
    }

}